import { VxeUI } from 'vxe-pc-ui';
import { ElButton } from 'element-plus';

/**
 * 获取属性值的通用函数
 * @param {string} attrName - 属性名
 * @param {*} defaultValue - 默认值
 * @param {Object} sources - 属性来源对象数组
 * @returns {*} 属性值
 */
const getAttributeValue = (attrName, defaultValue, ...sources) => {
  for (const source of sources) {
    if (source && source[attrName] !== undefined) {
      return source[attrName];
    }
  }
  return defaultValue;
};

/**
 * 渲染按钮组的通用函数
 * @param {Object} renderOpts - 渲染选项
 * @param {Object} params - 参数对象
 * @returns {JSX.Element} 渲染结果
 */
const renderButtonGroup = (renderOpts, params) => {
  // 确定有效的数据和列上下文
  const effectiveData = params?.row || renderOpts.row || renderOpts.data || {};
  const effectiveColumn = params?.column || renderOpts.column || {};
  const effectiveItem = params?.item || renderOpts.item || {};

  // 获取配置信息
  const props = renderOpts.props || {};
  const attrs = renderOpts.attrs || {};
  const itemRender = effectiveItem.itemRender || {};
  const events = itemRender.events || {};

  // 获取按钮配置数组
  const buttons = getAttributeValue(
    'buttons',
    [],
    props,
    attrs,
    itemRender,
    renderOpts,
  );

  // 获取容器样式配置
  const buttonSpacing = getAttributeValue(
    'buttonSpacing',
    '0px',
    props,
    attrs,
    itemRender,
    renderOpts,
  );
  const containerStyle = getAttributeValue(
    'containerStyle',
    {},
    props,
    attrs,
    itemRender,
    renderOpts,
  );
  const containerClass = getAttributeValue(
    'containerClass',
    '',
    props,
    attrs,
    itemRender,
    renderOpts,
  );
  const direction = getAttributeValue(
    'direction',
    'horizontal',
    props,
    attrs,
    itemRender,
    renderOpts,
  ); // horizontal | vertical
  const align = getAttributeValue(
    'align',
    'center',
    props,
    attrs,
    itemRender,
    renderOpts,
  ); // flex-start | center | flex-end
  const justify = getAttributeValue(
    'justify',
    'flex-start',
    props,
    attrs,
    itemRender,
    renderOpts,
  ); // flex-start | center | flex-end | space-between | space-around

  // 如果没有按钮配置，返回空
  if (!Array.isArray(buttons) || buttons.length === 0) {
    return null;
  }

  // 构建容器样式
  const finalContainerStyle = {
    display: 'flex',
    flexDirection: direction === 'vertical' ? 'column' : 'row',
    alignItems: align,
    justifyContent: justify,
    gap: buttonSpacing,
    ...containerStyle,
  };

  return (
    <div class={containerClass} style={finalContainerStyle}>
      {buttons.map((button, index) => {
        // 检查按钮是否应该显示（支持动态显示控制）
        const shouldShow =
          typeof button.visible === 'function'
            ? button.visible(effectiveData, params, button, index)
            : button.visible !== false;

        if (!shouldShow) {
          return null;
        }

        // 检查按钮是否应该禁用（支持动态禁用控制）
        const isDisabled =
          typeof button.disabled === 'function'
            ? button.disabled(effectiveData, params, button, index)
            : button.disabled || false;

        // 获取按钮文本（支持动态文本）
        const buttonText =
          typeof button.content === 'function'
            ? button.content(effectiveData, params, button, index)
            : button.content || '';

        // 获取按钮图标（支持动态图标）
        const buttonIcon =
          typeof button.icon === 'function'
            ? button.icon(effectiveData, params, button, index)
            : button.icon;

        // 构建按钮点击事件处理器
        const handleClick = (event) => {
          // 阻止事件冒泡（可配置）
          if (button.stopPropagation !== false) {
            event.stopPropagation();
          }

          // 执行按钮自定义点击事件
          if (button.onClick && typeof button.onClick === 'function') {
            button.onClick(effectiveData, params, button, index, event);
          }

          // 触发渲染器级别的按钮点击事件
          if (events.buttonClick && typeof events.buttonClick === 'function') {
            events.buttonClick(effectiveData, params, button, index, event);
          }
        };

        // 构建按钮属性
        const buttonProps = {
          key: button.key || index,
          type: getAttributeValue(
            'type',
            'default',
            button,
            props,
            attrs,
            itemRender,
            renderOpts,
          ),
          size: getAttributeValue(
            'size',
            undefined,
            button,
            props,
            attrs,
            itemRender,
            renderOpts,
          ),
          text: getAttributeValue(
            'text',
            undefined,
            button,
            props,
            attrs,
            itemRender,
            renderOpts,
          ),
          plain: getAttributeValue(
            'plain',
            false,
            button,
            props,
            attrs,
            itemRender,
            renderOpts,
          ),
          round: getAttributeValue(
            'round',
            false,
            button,
            props,
            attrs,
            itemRender,
            renderOpts,
          ),
          circle: getAttributeValue(
            'circle',
            false,
            button,
            props,
            attrs,
            itemRender,
            renderOpts,
          ),
          loading:
            typeof button.loading === 'function'
              ? button.loading(effectiveData, params, button, index)
              : getAttributeValue(
                  'loading',
                  false,
                  button,
                  props,
                  attrs,
                  itemRender,
                  renderOpts,
                ),
          disabled: isDisabled,
          icon: buttonIcon,
          autofocus: getAttributeValue(
            'autofocus',
            false,
            button,
            props,
            attrs,
            itemRender,
            renderOpts,
          ),
          nativeType: getAttributeValue(
            'nativeType',
            'button',
            button,
            props,
            attrs,
            itemRender,
            renderOpts,
          ),
          autoInsertSpace: getAttributeValue(
            'autoInsertSpace',
            false,
            button,
            props,
            attrs,
            itemRender,
            renderOpts,
          ),
          color: getAttributeValue(
            'color',
            '',
            button,
            props,
            attrs,
            itemRender,
            renderOpts,
          ),
          dark: getAttributeValue(
            'dark',
            false,
            button,
            props,
            attrs,
            itemRender,
            renderOpts,
          ),
          link: getAttributeValue(
            'link',
            false,
            button,
            props,
            attrs,
            itemRender,
            renderOpts,
          ),
          tag: getAttributeValue(
            'tag',
            'button',
            button,
            props,
            attrs,
            itemRender,
            renderOpts,
          ),
          style: getAttributeValue(
            'style',
            {},
            button,
            props,
            attrs,
            itemRender,
            renderOpts,
          ),
          class: getAttributeValue(
            'class',
            '',
            button,
            props,
            attrs,
            itemRender,
            renderOpts,
          ),
          onClick: handleClick,
        };

        // 过滤掉值为null、undefined或空字符串的属性
        const filteredProps = Object.fromEntries(
          Object.entries(buttonProps).filter(
            ([key, value]) =>
              value !== null && value !== undefined && value !== '',
          ),
        );

        // 渲染按钮图标
        if (typeof buttonIcon === 'string' && buttonIcon.startsWith('svg-')) {
          const iconName = '#' + buttonIcon.replace('svg-', 'icon-');
          return (
            <ElButton {...filteredProps}>
              <svg class="button-svg-icon">
                <use xlinkHref={iconName} />
              </svg>
              {buttonText}
            </ElButton>
          );
        } else {
          return (
            <ElButton {...filteredProps} icon={buttonIcon}>
              {buttonText}
            </ElButton>
          );
        }
      })}
    </div>
  );
};

// 注册支持多种上下文的渲染器
VxeUI.renderer.add('RaElButtonSetRender', {
  // 表格单元格编辑模式
  renderTableEdit(renderOpts, params) {
    return renderButtonGroup(renderOpts, params);
  },

  // 表格单元格显示模式
  renderTableCell(renderOpts, params) {
    return renderButtonGroup(renderOpts, params);
  },

  // 表单项目渲染
  renderItemContent(renderOpts, params) {
    return renderButtonGroup(renderOpts, params);
  },

  // 默认显示模式
  renderDefault(renderOpts, params) {
    return renderButtonGroup(renderOpts, params);
  },
});

export default 'RaElButtonSetRender';
